package nettcpchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

	private int port;

	public TCPServer(int port) {
		super();
		this.port = port;
		Server server = new Server();
		Thread thread = new Thread(server);
		thread.start();
	}

	class Server implements Runnable {

		@Override
		public void run() {
			ServerSocket serverSocket = null;
			Socket socket = null;
			BufferedReader br = null;
			try {
				serverSocket = new ServerSocket(port);
				socket = serverSocket.accept();
				InetAddress ia = socket.getInetAddress();
				InputStream inputStream = socket.getInputStream();
				br = new BufferedReader(new InputStreamReader(inputStream));
				String line = null;
				while ((line = br.readLine()) != null) {
					System.out.println(ia.getHostAddress() + " 说：" + line);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (br != null) {
						br.close();
					}
					if (socket!=null) {
						socket.close();
					}
					if (serverSocket!=null) {
						serverSocket.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	public static void main(String[] args) {
		TCPServer tcpServer = new TCPServer(10000);
	}
}
